package com.framework.workflow.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.framework.common.exception.BusinessException;
import com.framework.workflow.service.IResourceService;
import org.apache.commons.lang3.StringUtils;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.repository.Model;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;

@Service
public class ResourceService implements IResourceService {
    protected static final Logger LOGGER = LoggerFactory.getLogger(ResourceService.class);

    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private ObjectMapper objectMapper;


    @Override
    public void save(String modelId, String name, String xml) {
        try {
            Model model = repositoryService.getModel(modelId);
            ObjectNode modelJson = (ObjectNode) objectMapper.readTree(model.getMetaInfo());

            // 新增版本
            int version = model.getVersion() + 1;
            model.setVersion(version);
            model.setMetaInfo(modelJson.toString());
            model.setName(name);

            repositoryService.saveModel(model);
            repositoryService.addModelEditorSource(model.getId(), xml.getBytes(StandardCharsets.UTF_8));
        } catch (Exception e) {
            LOGGER.error("Error saving model", e);
            throw new BusinessException("Error saving model", e);
        }
    }

    @Override
    public String getXml(String modelId) {
        byte[]  xmlByte = repositoryService.getModelEditorSource(modelId);
        if (null != xmlByte) {
            return new String(xmlByte, StandardCharsets.UTF_8);
        }

        return StringUtils.EMPTY;
    }
}
